package xserver.codec;

import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import xgame.AbstractXresult;
import xgame.XpropertyContainer;

/**
 * 结果编码器
 * 
 * @author AfritXia
 * @version $Rev: 17 $
 *
 */
public class ResultEncoder extends ProtocolEncoderAdapter {
	/**
	 * 序列化器
	 * 
	 */
	private JSONSerializer _serializer = null;

	/**
	 * 类默认构造器
	 * 
	 */
	public ResultEncoder() {
		this._serializer = new JSONSerializer();
	}

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput output) {
		if (message == null || output == null) {
			return;
		}

		AbstractXresult result = (AbstractXresult)message;

		// 消息体
		XpropertyContainer bodyC = result.serialize();

		if (bodyC == null) {
			return;
		}

		// 根容器
		XpropertyContainer rootC = new XpropertyContainer();

		// 设置结果 Id
		rootC.putInt(AbstractXresult.RESULT_ID, result.getId());
		// 设置结果本身
		rootC.putPropertyContainer(AbstractXresult.RESULT_BODY, bodyC);

		// 将属性容器序列化为字节
		byte[] bytes = this._serializer.serialize(rootC);

		if (bytes == null) {
			return;
		}

		// 创建字节缓存
		ByteBuffer buff = ByteBuffer.allocate(bytes.length);
		
		buff.put(bytes);
		buff.flip();

		// 写出缓存
		output.write(buff);
	}
}
